local args = ngx.req.get_uri_args()

local act_id = args.act_id

if nil == act_id then
    ngx.say([[{"code":10000,"message":"act_id不能为空"}]])
    return
end

local type = args.type

if nil == type then
    ngx.say([[{"code":10000,"message":"type不能为空"}]])
    return
end

local redis_client = require "lib.redis"
local redis = redis_client:new()

local summary, err = redis:get(type..":"..act_id)

if err ~= nil then
    ngx.say('{"code":10000,"message":"redis error:', err,'"}')
    return
end

if nil == summary then
    ngx.say([[{"code":10000,"message":"活动不存在"}]])
    return
end

local participants = 0
local joins, err = redis:get("participants:"..act_id)

if err == nil then
    participants = tonumber(joins) or 0
end

local uid = args.uid
local surplus_times = 0

if nil ~= uid and "" ~= uid then
    local rules, err = redis:hmget('rules:'..act_id, 'limit_type', 'limit_times')

    if err ~= nil then
        ngx.say([[{"code":10000,"message":"活动不存在"}]])
        return
    end

    local mode = rules[1]
    local limit_times = tonumber(rules[2])
    local times_key = "times:"..act_id..":"..uid

    if mode == 'day' then
        local times_of_everday = redis:hget(times_key, ngx.today())
        local t = tonumber(times_of_everday) or 0
        surplus_times = limit_times - t
    else
        local times_of_life = redis:hget(times_key, 'total')
        local t = tonumber(times_of_life) or 0
        surplus_times = limit_times - t
    end
end

ngx.say('{"code":200,"message":"success","data":{"activity":', summary,',"participants":', participants)
ngx.say(',"surplus_times":', surplus_times)
ngx.say('}}')
